import { Message, requestLogger } from '@/libs/index';
import { AxiosResponse } from 'axios';
import { BusinessCode } from './code';
// import { NetCode, BusinessCode } from '../axios/code';
import { ResponseDataType } from './types/index';

/**
 * 设置响应拦截器
 * @param response axios响应内容
 * @returns
 */
// 出现兼容性问题，此处使用async+await，ios无法进入resolve状态，估计是axios问题？
export const setResponseConfig = (response: AxiosResponse<ResponseDataType>): Promise<AxiosResponse> => {
  console.log('response', response);

  // 控制台输出日志
  requestLogger({
    url: `${response.config.baseURL}${response.config.url}`,
    headers: response.config.headers,
    method: response.config.method,
    params: response.config.params,
    data: response.config.data,
    response: response,
    request: response.config
  });

  if (!response?.data) {
    if ((response as AxiosResponse & { errMsg: string }).errMsg) {
      throw new Error((response as AxiosResponse & { errMsg: string }).errMsg);
    }
    throw new Error('response.data is null/undefined!');
  }
  const data = response?.data;
  if (data?.code !== 200) {
    // 这个部分用于处理业务状态码非200状态下的错误处理
    try {
      BusinessCode?.dealBusinessError?.[data.code]?.(data);
    } catch (error) {
      console.error(error);
    }
    if (Number(data?.code) === 401) {
      return Message.error('请登录！').then(() => {
        // BusinessCode.dealBusinessError[data?.code] && BusinessCode.dealBusinessError[data?.code](data?.msg || data?.msg);
        return Promise.reject(data);
      });
    }
    return Message.error(data?.message).then(() => {
      // BusinessCode.dealBusinessError[data?.code] && BusinessCode.dealBusinessError[data?.code](data?.msg || data?.msg);
      return Promise.reject(data);
    });
  }
  return Promise.resolve(response);
};

export const setResponseError = (error: any): Promise<ResponseDataType> => {
  if (error.config) {
    const config = error.config;
    // 控制台输出日志
    requestLogger({
      url: `${config.baseURL}${config.url}`,
      headers: config.headers,
      method: config.method,
      params: config.params,
      data: config.data,
      response: JSON.parse(JSON.stringify(error)),
      request: config
    });
  }
  // const errMessage = NetCode.getErroMessage(error && error.response && error.response.status);
  return Message.error('出现错误').then(() => {
    return Promise.reject({
      code: (error && error.response && error.response.status) || 500,
      message: '出现错误'
    } as ResponseDataType);
  });
};
